<?php
/* Маппер лавжорнала
 * тут начинается бред
 * c этим я не знаю что делать 
 */
class Model_PostsLiveJournalMapper
{
    protected $_XmlRpcClient;
    protected $_ljUsername='username';
    protected $_ljPassword='userpass';
    public function __construct($XmlRpcClient = null)
    {
        if($XmlRpcClient === null){
            $this->_XmlRpcClient = new Zend_XmlRpc_Client('http://www.livejournal.com/interface/xmlrpc');
        } else {
            $this->_XmlRpcClient = $XmlRpcClient;
        }
    }
    //входящий параметр пост который в блоге
    public function save($post)
    {

       
        $chalengeResponse = $this->_XmlRpcClient->call('LJ.XMLRPC.getchallenge');
        $syncTable = new Model_DbTable_Sync();
              
        /*
         *  смотрим есть ли в таблице где хранится соотношение постов в блоге / пост в жж
         *   есть ли запись о посте в жж к такому то посту в блоге
         */
        $syncRow = $syncTable->fetchRow(array('post_id = ?' => (integer) $post->id));
        
        $ljId= $syncRow->lj_id;
        // если id жж не найденно 
        if($ljId===null){
            $chalengeResponse = $this->_XmlRpcClient->call('LJ.XMLRPC.getchallenge');
            $request = new Zend_XmlRpc_Request();
            $request->setMethod('LJ.XMLRPC.postevent');
            $stuctOptions = new Zend_XmlRpc_Value_Struct(
            array(
                        'username'       => $this->_ljUsername,
                        'auth_method'    => 'challenge',
                        'auth_challenge' => $chalengeResponse['challenge'],
                        'auth_response'  => md5($chalengeResponse['challenge'] . md5($this->_ljPassword)),
                        'ver'            =>'1',
                        'event'          => $post->text,
                        'subject'        => $post->title,
                        'year'           => 2010,
                        'mon'            => 1,
                        'day'            => 3,
                        'hour'           => 4,
                        'min'            => 33,
                        'props'          => array(
                                            'opt_preformatted' => true,
                                            'opt_backdated'    => true,
                                            'taglist'          => $post->blog->name
                        ),
                        'security'       =>'public'
                        ));
                        $request->addParam($stuctOptions);
                        $this->_XmlRpcClient->doRequest($request);
                        $data =  $this->_XmlRpcClient->getLastResponse()->getReturnValue();
                        $syncTable = new Model_DbTable_Sync();
                        // то добавляем пост и в таблицу с синхронизацией пишем его id
                        $syncTable->update(array('lj_id'=>$data['itemid']), array('post_id = ?' => (integer) $syncRow->post_id) );
        } else {
            // инче
            $request = new Zend_XmlRpc_Request();
            $request->setMethod('LJ.XMLRPC.editevent');
            $stuctOptions = new Zend_XmlRpc_Value_Struct(
            array(
                        'itemid'         => $ljId,
                        'username'       => $this->_ljUsername,
                        'auth_method'    => 'challenge',
                        'auth_challenge' => $chalengeResponse['challenge'],
                        'auth_response'  => md5($chalengeResponse['challenge'] . md5($this->_ljPassword)),
                        'ver'            =>'1',
                        'event'          => $post->text,
                        'subject'        => $post->title,
                        'security'       =>'public'
                        ));
                        $request->addParam($stuctOptions);
                        $this->_XmlRpcClient->doRequest($request);
                        //просто обновляем
                        $data =  $this->_XmlRpcClient->getLastResponse()->getReturnValue();
        }
    }
    //тут тоже входит пост который из блога со своим id
    public function delete($post)
    {
        $syncTable = new Model_DbTable_Sync();
        $syncRow = $syncTable->fetchRow(array('post_id = ?' => (integer) $post->id));
        $chalengeResponse = $this->_XmlRpcClient->call('LJ.XMLRPC.getchallenge');
        $request = new Zend_XmlRpc_Request();
        $request->setMethod('LJ.XMLRPC.editevent');
        $stuctOptions = new Zend_XmlRpc_Value_Struct(
        array(
                        'itemid'         => $syncRow->lj_id,
                        'username'       => $this->_ljUsername,
                        'auth_method'    => 'challenge',
                        'auth_challenge' => $chalengeResponse['challenge'],
                        'auth_response'  => md5($chalengeResponse['challenge'] . md5($this->_ljPassword)),
                        'ver'            =>'1',
        ));
        $request->addParam($stuctOptions);
        $this->_XmlRpcClient->doRequest($request);
        $data =  $this->_XmlRpcClient->getLastResponse()->getReturnValue();
    }

    public function getAllPosts()
    {
        $chalengeResponse = $this->_XmlRpcClient->call('LJ.XMLRPC.getchallenge');
        $request = new Zend_XmlRpc_Request();
        $request->setMethod('LJ.XMLRPC.getevents');
        $stuctOptions = new Zend_XmlRpc_Value_Struct(
        array(
                        'username'       => $this->_ljUsername,
                        'auth_method'    => 'challenge',
                        'auth_challenge' => $chalengeResponse['challenge'],
                        'auth_response'  => md5($chalengeResponse['challenge'] . md5($this->_ljPassword)),
                        'ver'            => 1,
                        'lineendings'    => 'unix',
                        'selecttype'     => 'lastn',
                        'lastsync'        => '2010-01-01 00:00:00',
                        'item_id'        => -1
        ));
        $request->addParam($stuctOptions);
        $this->_XmlRpcClient->doRequest($request);
        $result =  $this->_XmlRpcClient->getLastResponse()->getReturnValue();
        foreach($result['events'] as $ljPost){
            $posts[] = new Model_Post(array(
                  'title'   => $ljPost['subject'],
                  'text'    => $ljPost['event'],
                  'date'    => $ljPost['eventtime'],
                  'id'      => $ljPost['itemid'],
                  'blog_id' => 25
            ));
        }
        return $posts;
    }
}